<?php
  include("DBConfig.class.php");
  class District{

    public function getDistrict($value){

      //Query Province
      try {
        $db = new PDO("mysql:host=".DBConfig::$dbhost.";dbname=".DBConfig::$dbname, 
                      DBConfig::$dbuser, 
                      DBConfig::$dbpass, 
                      array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
                  );
        $db->setAttribute( PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );

        $value['proc'] = urldecode($value['proc']);
        $sql = "SELECT 
                  dis_id,
                  dis_province_code,
                  dis_code,
                  dis_name,
                  dis_lat,
                  dis_lon
                FROM ".DBConfig::$dbname.".district
                WHERE dis_province_code = :proc
                ORDER BY dis_id ASC";
        $stmt = $db->prepare($sql);
        $stmt->bindParam( ':proc', $value['proc'], PDO::PARAM_STR );

        $stmt->execute();
        $result = $stmt->fetchAll();

        if(!empty($result)){
          $response['votename'] = $value['votename'];
          $response['country'] = $value['country'];
          $response['layer'] = $result;
          $response['errorCode'] = 0;
          $response['errorString'] = "ok";
          $this->setDistrictResponse($response);
        } else{
          $response['errorCode'] = 102;
          $response['errorString'] = "District not found.";
          $this->setDistrictResponse($response);
        }

        /*** close the database connection ***/
        $db = null;
      }catch(PDOException $e) {
          //echo $e->getMessage();
          $response['errorCode'] = 5;
          $response['errorString'] = "Database cann't connect";
          $this->setDistrictResponse($response);
      }
    }

/*
    public function searchDistrict($value){

      //Query Province
      try {
        $db = new PDO("mysql:host=".DBConfig::$dbhost.";dbname=".DBConfig::$dbname, 
                      DBConfig::$dbuser, 
                      DBConfig::$dbpass, 
                      array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
                  );
        $db->setAttribute( PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );

        $sql = "SELECT 
                  dis_id,
                  dis_code,
                  dis_province_id,
                  dis_province_code,
                  dis_name,
                  dis_lat,
                  dis_lon
                FROM ".DBConfig::$dbname.".district
                WHERE dis_name like '%".$value['key']."%'
                GROUP BY dis_name
                ORDER BY dis_name ASC";
        $stmt = $db->prepare($sql);

        $stmt->execute();
        $result = $stmt->fetchAll();

        if(!empty($result)){
          $response['votename'] = $value['votename'];
          $response['country'] = $value['country'];
          $response['layer'] = $result;
          $response['errorCode'] = 0;
          $response['errorString'] = "ok";
          $this->setDistrictSearchResponse($response);
        } else{
          $response['errorCode'] = 102;
          $response['errorString'] = "District not found.";
          $this->setDistrictSearchResponse($response);
        }

        /*** close the database connection ***//*
        $db = null;
      }catch(PDOException $e) {
          //echo $e->getMessage();
          $response['errorCode'] = 5;
          $response['errorString'] = "Database cann't connect";
          $this->setDistrictSearchResponse($response);
      }
    }
*/

    public function setDistrictResponse($response){

        //Gen food
        $xml = new DOMDocument('1.0', 'UTF-8');
        $xml->formatOutput = true;

        $xml_node_datas = $xml->createElement("Datas");
        $xml->appendChild( $xml_node_datas);

        if($response['errorCode'] == 0){

          $xml_node_country = $xml->createElement("country",$response['country']);
          $xml_node_datas->appendChild( $xml_node_country);

          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );


            ////////////////////////////////////////////////
            //XML : node Map Tab
            ////////////////////////////////////////////////

            $xml_node_data = $xml->createElement("Data");
            $xml_node_data->setAttribute("id", 1);
            $xml_node_datas->appendChild( $xml_node_data);


            $xml_node_type = $xml->createElement("type","tab");
            $xml_node_data->appendChild( $xml_node_type);


            $xml_node_title = $xml->createElement("title", "แผนที่สรุปผลแบ่งตามอำเภอ");
            $xml_node_data->appendChild( $xml_node_title);

            //$xml_node_tab1 = $xml->createElement("tab1", htmlentities("http://192.168.1.9/govss/map/map1.html"));
            //$xml_node_data->appendChild( $xml_node_tab1);

            $xml_node_tab1 = $xml->createElement("tab1",  htmlentities($this->nextTabURL()."&type=map&data="));
            $xml_node_data->appendChild( $xml_node_tab1);

            //$xml_node_tab2 = $xml->createElement("tab2", htmlentities("http://192.168.1.9/govss/map/map2.html"));
            //$xml_node_data->appendChild( $xml_node_tab2);

            $xml_node_tab2 = $xml->createElement("tab2",  htmlentities($this->nextTabURL()."&type=map&data="));
            $xml_node_data->appendChild( $xml_node_tab2);

            //$xml_node_tab3 = $xml->createElement("tab3", htmlentities("http://192.168.1.9/govss/map/map3.html"));
            //$xml_node_data->appendChild( $xml_node_tab3);

            $xml_node_tab3 = $xml->createElement("tab3",  htmlentities($this->nextTabURL()."&type=map&data="));
            $xml_node_data->appendChild( $xml_node_tab3);

          $count = 2;
          foreach($response['layer'] as $val){
            //Check thai country 
            if($response['country'] == "TH"){
              $string = "อำเภอ";
              if(strstr($val['dis_name'],$string)){
                $district = $val['dis_name'];
              }else{
                $district = "อำเภอ".$val['dis_name'];
              }
            }else{
              $district = $val['dis_name'];
            }

            $xml_node_data = $xml->createElement("Data");
            $xml_node_data->setAttribute("id", $count++);
            $xml_node_datas->appendChild( $xml_node_data);

            $xml_node_type = $xml->createElement("type","list");
            $xml_node_data->appendChild( $xml_node_type);

            $xml_node_title = $xml->createElement("title", $district);
            $xml_node_data->appendChild( $xml_node_title);

            $arg = array(
                          'proc' => $val['dis_province_code'],
                          'disc' => $val['dis_code']
                        );
            $xml_node_xml = $xml->createElement("xml", htmlentities($this->getNextURL("district", "tambon", $arg)));
            $xml_node_data->appendChild( $xml_node_xml);




          }
        }else{
          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );
        }




        echo $xml->saveXML();
    }

/*
    public function setDistrictSearchResponse($response){

        //Gen food
        $xml = new DOMDocument('1.0', 'UTF-8');
        $xml->formatOutput = true;

        $xml_node_datas = $xml->createElement("Datas");
        $xml->appendChild( $xml_node_datas);

        if($response['errorCode'] == 0){

          $xml_node_country = $xml->createElement("country",$response['country']);
          $xml_node_datas->appendChild( $xml_node_country);

          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );

          $count = 1;
          foreach($response['layer'] as $val){

            $xml_node_data = $xml->createElement("Data");
            $xml_node_data->setAttribute("id", $count++);
            $xml_node_datas->appendChild( $xml_node_data);

            $xml_node_type = $xml->createElement("type","list");
            $xml_node_data->appendChild( $xml_node_type);

            //Check thai country 
            if($response['country'] == "TH"){
              $string = "อำเภอ";
              if(strstr($val['dis_name'],$string)){
                $district = $val['dis_name'];
              }else{
                $district = "อำเภอ".$val['dis_name'];
              }
            }else{
              $district = $val['dis_name'];
            }

            $xml_node_title = $xml->createElement("title", $district);
            $xml_node_data->appendChild( $xml_node_title);

            $arg = array(
                          'pro' => $val['dis_province_id'],
                          'dis' => $val['dis_id']
                        );
            $xml_node_xml = $xml->createElement("xml", htmlentities($this->getNextURL("district", "tambon", $arg)));
            $xml_node_data->appendChild( $xml_node_xml);

          }
        }else{
          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );
        }

        echo $xml->saveXML();
    }
*/


    public function getNextURL($currentLayer, $nextLayer, $arg){
      $page_url = 'http';
      if ($_SERVER['HTTPS'] == "on") {$pageURL .= "s";}
        $page_url .= "://";
      if ($_SERVER['SERVER_PORT'] != "80") {
        $page_url .= $_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'];
      } else {
        $page_url .= $_SERVER['SERVER_NAME'];
      }
      $explode_key = explode("&key",$_SERVER['REQUEST_URI']);
      $explode_pro = explode("&pro",$explode_key[0]);
      $new_url = str_replace("filter=".$currentLayer, "filter=".$nextLayer, $explode_pro[0]);
      foreach($arg as $key=>$val){
        $uri[] = $key."=".urlencode($val);
      }
      $uri = implode("&", $uri);

      return $page_url.$new_url."&".$uri;
    }

    public function nextTabURL(){
      $page_url = 'http';
      if ($_SERVER['HTTPS'] == "on") {$pageURL .= "s";}
        $page_url .= "://";
      if ($_SERVER['SERVER_PORT'] != "80") {
        $page_url .= $_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
      } else {
        $page_url .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
      }
      return $page_url;
    }


  }


?>